package com.example.thegreatwall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.thegreatwall.common.R;
import com.example.thegreatwall.entity.Comment;
import com.example.thegreatwall.entity.Users;
import com.example.thegreatwall.service.CommentService;
import com.example.thegreatwall.service.UsersService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@RequestMapping("/comment")
@CrossOrigin(origins = "*") //无论什么源都可以访问  不写这个不允许跨域
@RestController
public class CommentController{
    @Autowired
    private CommentService commentService;
    @Autowired
    private UsersService usersService;

    /**
     * 获得产品评论
     * @param pid 产品id
     * @param ptype 产品类型 0-单品 1-套餐
     * @return
     */
    @GetMapping("/getProductComment")
    public R getProductComment(@Param("pid") int pid,int ptype){
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", pid).and(i->i.eq("product_type", ptype)).orderByDesc("create_at");
        List<Comment> list = commentService.list(queryWrapper);
        //查询发送评论的用户信息
        list.forEach(item->{
            QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
            usersQueryWrapper.eq("user_id", item.getUserId());
            Users one = usersService.getOne(usersQueryWrapper);
            item.setUser(one);
        });
        return new R().addDate("list", list);
    }

    @GetMapping(value = "clearljt")
    public int clearljt(@RequestParam int id){
     return commentService.removeById(id)?1:0;
    }

    /**
     * 添加评论
     * @param comment 评论对象
     * @return
     */
    @PostMapping("/addComment")
    public R addComment(@RequestBody Comment comment){
        boolean save = commentService.save(comment);
        if(save){
            return new R().addDate("msg", "评论成功！");
        }else {
            return new R().addDate("msg", "评论失败！");
        }
    }

}